import {request} from "../../request/index.js"
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodsObj:{}
    },
    //商品全局对象
    GoodsInfo:{},

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const {goods_id} = options;
   
        this.getGoodDetail(goods_id);
    },
    async getGoodDetail(goods_id){
        const goodsObj = await request({url:"/goods/detail",data:{goods_id}});
        this.GoodsInfo =goodsObj;
        this.setData({
            goodsObj:{
                //只使用用得到的数据
                goods_name:goodsObj.goods_name,
                goods_price:goodsObj.goods_price,
                 //iPhone不识别webp格式图片
                goods_introduce:goodsObj.goods_introduce.replace(/\.webp/g,'.jpg'),
                pics:goodsObj.pics
               
            }
            
        })
    },
    // 点击轮播图放大预览
    clickSwiper(e){
        //生成图片数组
        const urls = this.GoodsInfo.pics.map(v=>v.pics_mid)
        //接受传递过来的图片路径
        const current = e.currentTarget.dataset.url;
        wx-wx.previewImage({
          urls,
          current,
          
        })
    },
    // 加入购物车
    joinCart(){
        // 获取缓存的数组
        let cart= wx.getStorageSync('cart')||[];
        // 商品是否存在购物车数组
        let index = cart.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id);
        if(index==-1){
            // 不存在
            this.GoodsInfo.num=1;
            this.GoodsInfo.checked=true;
            cart.push(this.GoodsInfo);
        }else{
            cart[index].num++;
        }
        // 购物车重新添加缓存
        wx.setStorageSync('cart', cart);
        // 提示
        wx.showToast({
          title: '加入成功',
          icon:'success',
          mask:true //防止以后手抖
        })
    },

    joinBuy(){
        wx.switchTab({
          url:'/pages/cart/index',
        })
    },

   
})